package com.tanhua.sso.controller;


import com.tanhua.common.pojo.User;
import com.tanhua.common.utils.NoAuthorization;
import com.tanhua.sso.service.UserService;
import com.tanhua.common.vo.ErrorResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

//短信校验接口
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    //手机号验证码校验
    @PostMapping("loginVerification")
    @NoAuthorization
    public ResponseEntity<Object> login(@RequestBody Map<String, String> param) {
        try {
            String phone = param.get("phone");
            String verificationCode = param.get("verificationCode");
            //返回null或者字符串,null即Error
            String login = userService.login(phone, verificationCode);
            /* ErrorResult errorResult = JSON.parseObject(login, ErrorResult.class);*/
            if (login != null) {
                Map<String, Object> result = new HashMap<>(2);
                //根据 | 来对split进行分割, | 前后互为一个数据
                String[] split = StringUtils.split(login, "|");
                result.put("token", split[0]);
                result.put("isNew", Boolean.valueOf(split[1]));
                return ResponseEntity.ok(result);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        ErrorResult errorResult = ErrorResult.builder().errCode("005").errMessage("登录失败！").build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }

    //外部访问接口直接获取到user路径后面的内容
    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token") String token) {
        return this.userService.tokenCheck(token);
    }

}